package com.voucher.qiege.three;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
public class SecureDownloader {

    public static void download(String fdId, String savePath) throws Exception {
        String downloadUrl = String.format(
            "http://oa.mexingroup.com:9999/sys/attachment/sys_att_main/sysAttMain.do" +
            "?method=download&fdId=%s&downloadFlag=%d",
            URLEncoder.encode(fdId, "UTF-8"),
            System.currentTimeMillis()
        );

        HttpGet downloadRequest = new HttpGet(downloadUrl);
        downloadRequest.addHeader("Referer", "http://oa.mexingroup.com:9999/main.do");
        downloadRequest.addHeader("User-Agent", "Mozilla/5.0 (compatible; MyApp/1.0)");

        try (CloseableHttpResponse response = SessionManager.httpClient.execute(downloadRequest)) {
            // 验证响应是否为文件流
            Header contentType = response.getFirstHeader("Content-Type");
            System.out.println("Content-Type: " +contentType.getValue());
//            if (contentType == null ||
//                (!contentType.getValue().contains("octet-stream")
//                 && !contentType.getValue().contains("wordprocessingml"))) {
//                throw new RuntimeException("下载失败: " + EntityUtils.toString(response.getEntity()));
//            }

            // 保存文件
            try (InputStream is = response.getEntity().getContent();
                 FileOutputStream fos = new FileOutputStream(savePath)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
            }
            System.out.println("文件保存成功: " + savePath);
        }
    }
}
